import 'package:dio/dio.dart';
import 'custom_interceptor.dart';

class Request {
  static Request? _instance;

  Request._(String baseUrl, int timeOut) {
    _init(baseUrl, timeOut);
  }

  factory Request(String baseUrl, {int timeOut = 5}) {
    _instance ??= Request._(baseUrl, timeOut);
    return _instance!;
  }

  _init(String baseUrl, int timeOut) {
    // 配置基础信息
    _baseOptions = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: Duration(seconds: timeOut),
      receiveTimeout: Duration(seconds: timeOut),
    );
    // 初始化Dio
    _dio = Dio(_baseOptions);
    // 添加拦截器
    _dio.interceptors.add(CustomInterceptor());
  }

  late Dio _dio;

  late BaseOptions _baseOptions;

  Future<Response<T>> _request<T>(
    String url, {
    String method = "GET",
    Object? data,
    Map<String, dynamic>? query,
    Map<String, dynamic>? headers,
  }) async {
    Response<T> response = await _dio.request(url,
        data: data,
        queryParameters: query,
        options: Options(method: method, headers: headers));
    return response;
  }

  // get请求
  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? query,
    Map<String, dynamic>? headers,
  }) async {
    return await _request(
      path,
      method: "GET",
      query: query,
      headers: headers,
    );
  }

  // post请求
  Future<Response<T>> post<T>(String path,
      {Map<String, dynamic>? data,
      Map<String, dynamic>? query,
      Map<String, dynamic>? headers}) async {
    Response<T> resp = await _request(
      path,
      method: "POST",
      data: data,
      query: query,
      headers: headers,
    );
    return resp;
  }

  // put请求
  Future<Response<T>> put<T>(String path,
      {Map<String, dynamic>? data,
      Map<String, dynamic>? query,
      Map<String, dynamic>? headers}) async {
    Response<T> resp = await _request(
      path,
      method: "PUT",
      data: data,
      query: query,
      headers: headers,
    );
    return resp;
  }

  // delete请求
  Future<Response<T>> delete<T>(String path,
      {Map<String, dynamic>? data,
      Map<String, dynamic>? query,
      Map<String, dynamic>? headers}) async {
    Response<T> resp = await _request(
      path,
      method: "PUT",
      data: data,
      query: query,
      headers: headers,
    );
    return resp;
  }

  void upload() {}

  void download() {}
}
